package com.mojo.redisson.config;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenBucketInterceptor implements HandlerInterceptor {

    private final TokenBucketRateLimiter rateLimiter;

    public TokenBucketInterceptor(TokenBucketRateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (rateLimiter.allowRequest()) {
            return true; // 允许请求通过
        } else {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            response.getWriter().write("Too Many Requests");
            return false; // 请求限流
        }
    }
}
